#!/bin/bash

# source '/etc/os-release' > /dev/null

judge() {
    if [[ 0 -eq $? ]]; then
        echo -e "${OK} ${GreenBG} $1 完成 ${Font}"
        sleep 1
    else
        echo -e "${Error} ${RedBG} $1 失败 ${Font}" >&2
        exit 1
    fi
}

add_ssl() {
    local domain=$1
    if [[ -z "${domain}" ]]; then
      echo "域名错误"
      exit 0
    fi
    # if [[ "${ID}" == "centos" ]]; then
    #     yum install -y curl socat
    # else
    #     apt install -y curl socat
    # fi
    # judge "安装 SSL 证书生成脚本依赖"

    # 判断证书是否存在

    sslPath="/root/.sdwan/ssl/${domain}"
    mkdir -p "${sslPath}"

    if [[ -f ${sslPath}/site.crt ]] && [[ -s ${sslPath}/site.crt ]] && [[ "--no-repeat" == $2 ]];then
      echo "${sslPath}/site.crt 证书已存在"
      exit 0
    fi

    curl https://get.acme.sh | sh
    judge "安装 SSL 证书生成脚本"

    if [[ -f /root/.acme.sh/acme.sh ]]; then
      cmd=/root/.acme.sh/acme.sh
    else
      cmd=/.acme.sh/acme.sh
    fi

    $cmd --register-account -m admin@admin.com
    $cmd --issue -d "${domain}" --standalone
    $cmd --installcert -d "${domain}" --key-file "${sslPath}/site.key" --fullchain-file "${sslPath}/site.crt"
}

add_ssl $@
